
import PoolManager from "../../manager/PoolManager";
import Unit from "../Unit";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Bullet_Tracking extends cc.Component {

   
    target: Unit = null;

    fireFlag: boolean = false;

    bulletSpeed = 400;
    callback:Function = null;
    fire(unit:Unit,callback?:Function) {
        this.target = unit;
        this.callback = callback;
        this.node.active = true;
        this.fireFlag = true;
    }

    hitTheTarget() {
        if (this.callback) {
            this.callback();
            this.callback = null;
        }
        PoolManager.instance.put(this.node);
        this.fireFlag = false;
    }
    
    lateUpdate(dt) {
        if (!this.fireFlag) return;
        let targetPos: cc.Vec2 = this.target.node.getPosition();
        let bulletPos: cc.Vec2 = this.node.getPosition();
        let normalizeVec: cc.Vec2 = targetPos.subtract(bulletPos).normalize();

        this.node.x += normalizeVec.x * this.bulletSpeed * dt;
        this.node.y += normalizeVec.y * this.bulletSpeed * dt;
        
        this.node.angle = cc.v2(0, 1).signAngle(normalizeVec) * 180 / Math.PI;
        let rect = this.target.node.getBoundingBox();
        if (rect.contains(bulletPos)) this.hitTheTarget();
    }
}